package com.zqq.baselibrary.widgets

import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.FrameLayout
import android.widget.TextView
import android.widget.ViewFlipper
import com.zqq.baselibrary.R
import org.jetbrains.anko.dimen
import org.jetbrains.anko.find
import org.jetbrains.anko.px2sp

/**
 * 公告组件封装 (这是个简单的 广告轮播控件)
 * 参考--《我的下拉阻尼变大--MaqueenView》
 * @author zqq on 2019/5/26.
 */
class NewsFlipperView @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {

    private val mFlipperView: ViewFlipper

    init {
        val rootView = View.inflate(context, R.layout.layout_news_flipper, null)
        mFlipperView = rootView.find(R.id.mFlipperView)
        mFlipperView.setInAnimation(context, R.anim.news_bottom_in)
        mFlipperView.setOutAnimation(context, R.anim.news_bottom_out)

        addView(rootView)
    }

    //构建公告
    private fun buildNewsView(text: String): View {
        val textView = TextView(context)
        textView.text = text
//        textView.textSize = px2sp(dimen(R.dimen.text_small_size))//这个用的是anko里的
        textView.textSize = px2sp(R.dimen.text_small_size)
        textView.layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)

        return textView
    }


    //设置公告数据
    fun setData(data: Array<String>) {
        for (text: String in data) {
            mFlipperView.addView(buildNewsView(text))
        }
        mFlipperView.startFlipping()
    }


    private fun px2sp(resource: Int): Float {
        val px = resources.getDimensionPixelSize(resource)
        return px.toFloat() / resources.displayMetrics.scaledDensity
    }

}